﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Collections.Generic;
using System.Xml;
using ServBus.ListForm2010.Utility;
using System.IO;

namespace ServBus.ListForm2010.ListFormWebPart
{
    [ToolboxItemAttribute(false)]
    public class ListFormWebPart : WebPart
    {
        // 当更改可视 Web 部件项目项时，Visual Studio 可能会自动更新此路径。
        private const string AscxPath = @"~/_CONTROLTEMPLATES/ServBus.ListForm2010/ListFormWebPart/ListFormWebPartUserControl.ascx";
        
        protected override void CreateChildControls()
        {
            ListFormWebPartUserControl control = Page.LoadControl(AscxPath) as ListFormWebPartUserControl;
            if (control != null)
            {
                control.webpart = this;
            }
            if (control != null) Controls.Add(control);
        }


        #region Properties
        private bool _showRibbon = true;
        [WebBrowsable(true)]
        [WebDescription("ShowRibbon")]
        [WebDisplayName("ShowRibbon")]
        [Personalizable(PersonalizationScope.Shared)]
        public bool ShowRibbon
        {
            get { return _showRibbon; }
            set
            { _showRibbon = value;
            }
        }

        [WebDescription("ViewName")]
        [WebDisplayName("ViewName")]
        [Personalizable(PersonalizationScope.Shared)]
        public string ViewName { get; set; }

        
        //[WebBrowsable(true)]
        //[WebDescription("listId")]
        //[WebDisplayName("listId")]
        //[Personalizable(PersonalizationScope.Shared)]
        //public string listId { get; set; }

        //[WebBrowsable(true)]
        //[WebDescription("ctypeId")]
        //[WebDisplayName("ctypeId")]
        //[Personalizable(PersonalizationScope.Shared)]
        //public string ctypeId { get; set; }
        #endregion

        public override EditorPartCollection CreateEditorParts()
        {

            EditorPartCollection baseParts = base.CreateEditorParts();

            List<EditorPart> editorParts = new List<EditorPart>(1);

            EditorPart part = new MyEditorPart();

            part.ID = ID + "_tagValueEditor";

            part.Title = @"InfoPath Form";

            editorParts.Add(part);

            return new EditorPartCollection(baseParts, editorParts);

        }
    }



    #region EditorPart

    public class MyEditorPart : EditorPart
    {
        private DropDownList _ddlView;
        private CheckBox _cbShowRibbon;

        private readonly Dictionary<string, string> _urlParamDic = new Dictionary<string, string>();
        private void DecodeUrl()
        {
            String currurl = HttpUtility.UrlDecode(HttpContext.Current.Request.RawUrl.ToUpper());
            String querystring = null;

            // Check to make sure some query string variables
            // exist and if not add some and redirect.
            int iqs = currurl.IndexOf('?');
            if (iqs >= 0)
            {
                querystring = (iqs < currurl.Length - 1) ? currurl.Substring(iqs + 1) : String.Empty;
            }

            // Parse the query string variables into a NameValueCollection.
            if (querystring != null)
            {
                System.Collections.Specialized.NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);

                // Iterate through the collection.
                foreach (String s in qscoll.AllKeys)
                {
                    _urlParamDic.Add(s, qscoll[s]);
                }
            }
        }

        private string Request(string param)
        {
            string returnValue = string.Empty;

            if (_urlParamDic.ContainsKey(param.ToUpper()))
            {
                returnValue = _urlParamDic[param.ToUpper()];
            }
            return returnValue;
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            
            _cbShowRibbon = new CheckBox {Text = @"Show InfoPath Ribbon or toolbar<br />"};
            Label alterLine = new Label {Text = @"<div style='width:100%' class='UserDottedLine'></div>"};
            _ddlView = new DropDownList();
            Label lblView = new Label
            {
                Text = @"<br />Select the form view to display by default.<br /><br />Views:<br />"
            };
            IEnumerable<string> listViews = GetViews();
            foreach (string formView in listViews)
            {
                string formViewName = formView.Substring(formView.IndexOf('_') + 1);
                ListItem listItem = new ListItem(formViewName, formViewName);
                _ddlView.Items.Add(listItem);
                
            }
            Label alterLine1 = new Label {Text = @"<br /><br />"};
            Controls.Add(_cbShowRibbon);
            Controls.Add(alterLine);
            Controls.Add(lblView);
            Controls.Add(_ddlView);
            Controls.Add(alterLine1);
        }

        private IEnumerable<string> GetViews()
        {
            List<string> views;
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                {
                    DecodeUrl();
                    string ctypeId = Request("ctypeId");
                    string listId = Request("listId");
                    Guid guidListId = new Guid(listId);
                    SPList list = web.Lists[guidListId];
                    SPContentTypeId spContentTypeIdctypeId = new SPContentTypeId(ctypeId.ToLower());
                    SPContentType cType = list.ContentTypes[spContentTypeIdctypeId];
                    string xsnLocation = web.Url + "/" + cType.ResourceFolder.Url + "/template.xsn";
                    SPFile file = web.GetFile(xsnLocation);
                    byte[] xsnContent = file.OpenBinary();
                    XmlDocument xsfDoc = new XmlDocument();
                    XsnExtractor extractor = new XsnExtractor(xsnContent);
                    byte[] xsfContent = extractor.Extract("manifest.xsf");
                    using (MemoryStream xsfStream = new MemoryStream(xsfContent))
                    {
                        xsfDoc.Load(xsfStream);
                    }

                    // Validate Feature
                    FeatureChecker checker = new FeatureChecker(xsfDoc);
                    views = checker.ViewInfo;
                }
            }
            return views;
        }
        

        public override bool ApplyChanges()
        {
            EnsureChildControls();
            ListFormWebPart webPart = WebPartToEdit as ListFormWebPart;
            if (webPart != null)
            {
                webPart.ShowRibbon = _cbShowRibbon.Checked;
                webPart.ViewName = _ddlView.SelectedValue;

            }
            return true;
        }

        public override void SyncChanges()
        {
            EnsureChildControls();
            ListFormWebPart webPart = WebPartToEdit as ListFormWebPart;
            if (webPart != null)
            {
                _cbShowRibbon.Checked = webPart.ShowRibbon;
                _ddlView.SelectedValue = webPart.ViewName;
            }
        }
    }
    #endregion
}
